﻿using Domain.Entity;
using DtoFw;
using DtoFw.Query;
using Repository;
using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
using Util;
using System.Net.Http;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using SqlSugar;
using DtoFw.Enum;

namespace Service
{
    public class QueryService
    {

        private readonly CaseRepository _caseRepository;
        private readonly CasePhysicalEvidenceRepository _casePhysicalEvidenceRepository;
        private readonly MainOrganRepository _mainOrganRepository;
        public QueryService(CaseRepository caseRepository, CasePhysicalEvidenceRepository casePhysicalEvidenceRepository, MainOrganRepository mainOrganRepository)
        {
            this._caseRepository = caseRepository;
            this._casePhysicalEvidenceRepository = casePhysicalEvidenceRepository;
            this._mainOrganRepository = mainOrganRepository;
        }
        /// <summary>
        /// 查询案件
        /// </summary>
        /// <returns></returns>
        public BaseGenericResult<Pager<QueryCaseDto>> QueryCase(QueryCaseDto dto)
        {
            int total = 0;
            Pager<QueryCaseDto> pager = new Pager<QueryCaseDto>();
            var linq = _caseRepository.GetDb()
                 .Queryable<CaseEntity>()
                  .Where(x => !x.IsDeleted)
                    .WhereIF(!string.IsNullOrWhiteSpace(dto.CaseNo), x => x.CaseNo.Contains(dto.CaseNo))
                    .WhereIF(!string.IsNullOrWhiteSpace(dto.InspectionNo), x => x.InspectionNo.Contains(dto.InspectionNo))
                     .WhereIF(!string.IsNullOrWhiteSpace(dto.CaseName), x => x.CaseName.Contains(dto.CaseName))
                    .WhereIF(dto.CaseTimeStart.HasValue && dto.CaseTimeEnd.HasValue, x => x.CaseTime >= dto.CaseTimeStart && x.CaseTime <= dto.CaseTimeEnd.Value.AddDays(1))
                    .WhereIF(!string.IsNullOrWhiteSpace(dto.CaseTypeName), x => x.CaseTypeName.Contains(dto.CaseTypeName))
                    .WhereIF(!string.IsNullOrWhiteSpace(dto.HostUserName), x => x.HostUserName.Contains(dto.HostUserName))
                    .WhereIF(!string.IsNullOrWhiteSpace(dto.HostUserOrganName), x => x.HostUserOrganName.Contains(dto.HostUserOrganName))
                    .WhereIF(!string.IsNullOrWhiteSpace(dto.CasePlace), x => x.CasePlace.Contains(dto.CasePlace))
                    .WhereIF(!string.IsNullOrWhiteSpace(dto.BriefCase), x => x.BriefCase.Contains(dto.BriefCase))
                    .WhereIF(dto.Ty == "2", x => x.CreateTime >= Convert.ToDateTime(DateTime.Now.ToShortDateString()))
                    .OrderBy(x => x.CreateTime, OrderByType.Desc)
                    .ToPageList(dto.Page, dto.PageSize, ref total);

            pager.Data = AutoMapperExtension.MapTo<CaseEntity, QueryCaseDto>(linq);
            pager.TotalCount = total;

            return BaseGenericResult<Pager<QueryCaseDto>>.Succeed(pager);
        }

        /// <summary>
        /// 物品查询
        /// </summary>
        /// <returns></returns>
        public BaseGenericResult<Pager<QueryEvidenceDto>> QueryEvidence(QueryEvidenceDto dto)
        {
            int total = 0;
            Pager<QueryEvidenceDto> pager = new Pager<QueryEvidenceDto>();
            pager.Data = _caseRepository.GetDb()
                .Queryable<CaseEntity, CasePhysicalEvidenceEntity, CasePhysicalEvidenceTransfereEntity>
                ((t1, t2, t3) => new JoinQueryInfos(
                   JoinType.Left, t1.Id == t2.CaseId, JoinType.Left, t2.Id == t3.EvidenceId && t3.HistoryStatus == 0))
                  .Where((t1, t2, t3) => !t1.IsDeleted && !t2.IsDeleted)
                  .WhereIF(!string.IsNullOrWhiteSpace(dto.CaseNo), (t1, t2, t3) => t1.CaseNo.Contains(dto.CaseNo))
                  .WhereIF(!string.IsNullOrWhiteSpace(dto.InspectionNo), (t1, t2, t3) => t1.InspectionNo.Contains(dto.InspectionNo))
                  .WhereIF(!string.IsNullOrWhiteSpace(dto.CaseName), (t1, t2, t3) => t1.CaseName.Contains(dto.CaseName))
                  .WhereIF(!string.IsNullOrWhiteSpace(dto.Name), (t1, t2, t3) => t2.Name.Contains(dto.Name))
                  .WhereIF(!string.IsNullOrWhiteSpace(dto.No), (t1, t2, t3) => t2.No.Contains(dto.No))
                  .WhereIF(!string.IsNullOrWhiteSpace(dto.Class), (t1, t2, t3) => t2.Class == dto.Class)
                  .WhereIF(!string.IsNullOrWhiteSpace(dto.Category), (t1, t2, t3) => t2.Category == dto.Category)
                    .WhereIF(!string.IsNullOrWhiteSpace(dto.SubCategoryId), (t1, t2, t3) => t2.SubCategoryId == dto.SubCategoryId)
                  .WhereIF(dto.Status.HasValue && dto.Status >= 0, (t1, t2, t3) => t2.Status == dto.Status)
                  .WhereIF(!string.IsNullOrWhiteSpace(dto.source), (t1, t2, t3) => t2.Source.Contains(dto.source))
                  .WhereIF(!string.IsNullOrWhiteSpace(dto.Shape), (t1, t2, t3) => t2.Shape.Contains(dto.Shape))
                  .WhereIF(!string.IsNullOrWhiteSpace(dto.ExtractionOrganName), (t1, t2, t3) => t2.ExtractionOrganName.Contains(dto.Shape))
                  //.WhereIF(dto.ExtractionOrganId.HasValue && dto.ExtractionOrganId.Value > 0, (t1, t2, t3) => t2.ExtractionOrganId == dto.ExtractionOrganId)
                  .WhereIF(!string.IsNullOrWhiteSpace(dto.ExtractionPersonName), (t1, t2, t3) => t2.ExtractionPersonName.Contains(dto.ExtractionPersonName) || t2.ExtractionPerson1Nmae.Contains(dto.ExtractionPersonName))
                  .WhereIF(dto.ExtractionDateTimeStart.HasValue && dto.ExtractionDateTimeEnd.HasValue, (t1, t2, t3) => t2.ExtractionDateTime >= dto.ExtractionDateTimeStart && t2.ExtractionDateTime <= dto.ExtractionDateTimeEnd.Value.AddDays(1))
                  .WhereIF(!string.IsNullOrWhiteSpace(dto.ExtractMethod), (t1, t2, t3) => t2.ExtractMethod.Contains(dto.ExtractMethod))
                  .WhereIF(!string.IsNullOrWhiteSpace(dto.ExtractionParts), (t1, t2, t3) => t2.ExtractionParts.Contains(dto.ExtractionParts))
                  .WhereIF(!string.IsNullOrWhiteSpace(dto.Describe), (t1, t2, t3) => t2.Describe.Contains(dto.Describe))
                  .WhereIF(dto.CreateTimeStart.HasValue && dto.CreateTimeEnd.HasValue, (t1, t2, t3) => t2.CreateTime >= dto.CreateTimeStart && t2.CreateTime <= dto.CreateTimeEnd.Value.AddDays(1))
                  .WhereIF(dto.DeliveryDicType.HasValue && dto.DeliveryDicType > 0 && dto.DeliveryDicType == 8, (t1, t2, t3) => t3.DeliveryDicType == dto.DeliveryDicType || t3.DeliveryDicType == 7 || t3.DeliveryDicType == 6)
                   .WhereIF(dto.DeliveryDicType.HasValue && dto.DeliveryDicType > 0 && dto.DeliveryDicType != 8, (t1, t2, t3) => t3.DeliveryDicType == dto.DeliveryDicType)
                  .WhereIF(dto.Ty == "2" && dto.DeliveryDicType.HasValue && dto.DeliveryDicType > 0, (t1, t2, t3) => t3.CreateTime >= Convert.ToDateTime(DateTime.Now.ToShortDateString()))
                  .WhereIF(dto.Ty == "2" && dto.DeliveryDicType.HasValue && dto.DeliveryDicType==0, (t1, t2, t3) => t2.CreateTime >= Convert.ToDateTime(DateTime.Now.ToShortDateString()))
                  .OrderBy((t1, t2, t3) => t3.CreateTime, OrderByType.Desc)
                  .Select((t1, t2, t3) => new QueryEvidenceDto()
                  {
                      id = t1.Id,
                      CaseNo = t1.CaseNo,
                      InspectionNo = t1.InspectionNo,
                      CaseName = t1.CaseName,
                      No = t2.No,
                      Name = t2.Name,
                      Status = t2.Status,
                      Shape = t2.Shape,
                      Class = t2.Class,
                      ClassName = t2.ClassName,
                      Category = t2.Category,
                      CategoryName = t2.CategoryName,
                      Quantity = t2.Quantity,
                      Unit = t2.Unit,
                      EvidenceSource = t2.Source,
                      ExtractionParts = t2.ExtractionParts,
                      ExtractMethod = t2.ExtractMethod,
                      ExtractionPersonName = t2.ExtractionPersonName,
                      ExtractionDateTime = t2.ExtractionDateTime,
                      ExtractionOrganId = t2.ExtractionOrganId,
                      ExtractionOrganName = t2.ExtractionOrganName,
                      Describe = t2.Describe,
                      Location = t3.Location,
                      CreateTime = t2.CreateTime
                  })
                  .ToPageList(dto.Page, dto.PageSize, ref total);

            pager.TotalCount = total;

            return BaseGenericResult<Pager<QueryEvidenceDto>>.Succeed(pager);
        }

        /// <summary>
        /// 硕源查询
        /// </summary>
        /// <returns></returns>
        public BaseGenericResult<QuerySourceDto> QuerySource(QueryDto dto)
        {
            var result = new QuerySourceDto();
            result.SourceList = _caseRepository.GetDb()
                 .Queryable<CaseEntity, CasePhysicalEvidenceEntity, CasePhysicalEvidenceTransfereEntity>
                      ((t1, t2, t3) => new JoinQueryInfos(
                   JoinType.Left, t1.Id == t2.CaseId, JoinType.Left, t2.Id == t3.EvidenceId && t3.HistoryStatus == 0))
                  .Where((t1, t2) => !t1.IsDeleted && !t2.IsDeleted)
                    .WhereIF(!string.IsNullOrWhiteSpace(dto.caseNo), (t1, t2, t3) => t1.CaseNo == dto.caseNo)
                    .WhereIF(!string.IsNullOrWhiteSpace(dto.invNo), (t1, t2, t3) => t1.InspectionNo == dto.invNo)
                    .WhereIF(!string.IsNullOrWhiteSpace(dto.eviNo), (t1, t2, t3) => t2.No == dto.eviNo)
                  .Select((t1, t2, t3) => new QueryEvidenceDto()
                  {
                      id = t1.Id,
                      CaseNo = t1.CaseNo,
                      InspectionNo = t1.InspectionNo,
                      CaseName = t1.CaseName,
                      No = t2.No,
                      Name = t2.Name,
                      Status = t2.Status,
                      Shape = t2.Shape,
                      Class = t2.Class,
                      ClassName = t2.ClassName,
                      Category = t2.Category,
                      CategoryName = t2.CategoryName,
                      Quantity = t2.Quantity,
                      Unit = t2.Unit,
                      EvidenceSource = t2.SourceName,
                      ExtractionParts = t2.ExtractionParts,
                      ExtractMethod = t2.ExtractMethod,
                      ExtractionPersonName = t2.ExtractionPersonName,
                      ExtractionDateTime = t2.ExtractionDateTime,
                      ExtractionOrganId = t2.ExtractionOrganId,
                      ExtractionOrganName = t2.ExtractionOrganName,
                      Describe = t2.Describe,
                      Location = t3.Location,
                      CreateTime = t2.CreateTime,
                      OrganId = t2.OrganId
                  }).ToList();

            //硕源记录
            if (result.SourceList.Count > 0)
                result.SourceTimeLine = GetSource(result.SourceList.FirstOrDefault().No, (long)result.SourceList.FirstOrDefault().OrganId);

            return BaseGenericResult<QuerySourceDto>.Succeed(result);
        }

        /// <summary>
        /// 物品朔源查询
        /// </summary>
        /// <param name="eveidenceNo"></param>
        /// <param name="organId"></param>
        /// <returns></returns>
        private SourceEviDto GetSource(string eveidenceNo, long organId)
        {

            //查询案件
            SourceEviDto dto = _caseRepository.GetCaseEntityByEviNo(eveidenceNo, organId);
            if (dto != null)
            {
                MainOrganEntity organEntity = _mainOrganRepository.Query(new BaseQuery() { }, x => x.Where(v => v.Id == organId)).Single();

                dto.Data.Add(new SourceDto { Title = "案件信息", Time = dto.CaseTime, V1 = dto.HostUserOrganName, V2 = dto.HostUserName, V3 = dto.InspectionNo, V4 = dto.CaseNo });
                dto.Data.Add(new SourceDto { Title = "登记", Time = dto.CreateTime, V1 = organEntity.Name, V2 = dto.Creator, V3 = dto.InspectionNo, V4 = dto.CaseNo });


                List<CasePhysicalEvidenceTransfereEntity> transListEntity = _caseRepository.GetTansByEviNo(eveidenceNo, organId);
                foreach (var item in transListEntity)
                {
                    if (item.DeliveryDicType == 6)
                    {
                        //回库
                        dto.Data.Add(new SourceDto { Title = "回库", Time = item.CreateTime, V1 = item.Location, V2 = item.Transferor, V3 = item.Receiver });
                    }
                    else if (item.DeliveryDicType == 8)
                    {
                        //入库
                        dto.Data.Add(new SourceDto { Title = "入库", Time = item.CreateTime, V1 = item.Location, V2 = item.Transferor, V3 = item.Receiver });
                    }
                    else if (item.DeliveryDicType == 7)
                    {
                        //更换位置
                        dto.Data.Add(new SourceDto { Title = "位置转移", Time = item.CreateTime, V1 = item.Remark, V2 = item.Location, V3 = item.Creator });
                    }
                    else
                    {
                        //其他出库
                        dto.Data.Add(new SourceDto { Title = item.DeliveryDicTypeName, Time = item.CreateTime, V1 = item.ReceiverOrgan, V2 = item.Receiver, V3 = item.Transferor });
                    }
                }
            }

            return dto;
        }

        /// <summary>
        /// 一键查询
        /// </summary>
        /// <returns></returns>
        public BaseGenericResult<Pager<QueryEvidenceDto>> QueryInfo(string key, int page, int pageSize)
        {
            int total = 0;
            Pager<QueryEvidenceDto> pager = new Pager<QueryEvidenceDto>();
            pager.Data = _caseRepository.GetDb()
                .Queryable<CaseEntity, CasePhysicalEvidenceEntity, CasePhysicalEvidenceTransfereEntity>
                ((t1, t2, t3) => new JoinQueryInfos(JoinType.Left, t1.Id == t2.CaseId, JoinType.Left, t2.Id == t3.EvidenceId && t3.HistoryStatus == 0))
                  .Where((t1, t2, t3) => !t1.IsDeleted && !t2.IsDeleted)
                  .WhereIF(!string.IsNullOrWhiteSpace(key),
                  (t1, t2, t3) =>
                  t1.CaseNo.Contains(key) ||
                  t1.InspectionNo.Contains(key) ||
                  t1.CaseName.Contains(key) ||
                  t2.Name.Contains(key) ||
                  t2.No.Contains(key) ||
                  t2.ClassName.Contains(key) ||
                  t2.CategoryName.Contains(key) ||
                  t2.EvidenceSource.Contains(key) ||
                  t2.EvidenceSource.Contains(key) ||
                  t2.ExtractionPersonName.Contains(key) ||
                  t2.ExtractionPerson1Nmae.Contains(key) ||
                  t2.ExtractMethod.Contains(key) ||
                  t2.ExtractionParts.Contains(key) ||
                  t2.Describe.Contains(key))
                  .Select((t1, t2, t3) => new QueryEvidenceDto()
                  {
                      id = t1.Id,
                      CaseNo = t1.CaseNo,
                      InspectionNo = t1.InspectionNo,
                      CaseName = t1.CaseName,
                      No = t2.No,
                      Name = t2.Name,
                      Status = t2.Status,
                      Shape = t2.Shape,
                      Class = t2.Class,
                      ClassName = t2.ClassName,
                      Category = t2.Category,
                      CategoryName = t2.CategoryName,
                      Quantity = t2.Quantity,
                      Unit = t2.Unit,
                      EvidenceSource = t2.EvidenceSource,
                      ExtractionParts = t2.ExtractionParts,
                      ExtractMethod = t2.ExtractMethod,
                      ExtractionPersonName = t2.ExtractionPersonName,
                      ExtractionDateTime = t2.ExtractionDateTime,
                      ExtractionOrganId = t2.ExtractionOrganId,
                      ExtractionOrganName = t2.ExtractionOrganName,
                      Describe = t2.Describe,
                      Location = t3.Location,
                      CreateTime = t2.CreateTime,
                  })
                  .ToPageList(page, pageSize, ref total);

            pager.TotalCount = total;

            return BaseGenericResult<Pager<QueryEvidenceDto>>.Succeed(pager);
        }
    }
}
